Python控制函数运行时间多线程 您所在的位置:网站首页 python 线程超时 Python控制函数运行时间多线程

Python控制函数运行时间多线程

2024-07-10 21:37| 来源: 网络整理| 查看: 265

# -*- coding: utf-8 -*- from threading import Thread import time class TimeoutException(Exception): pass ThreadStop = Thread._Thread__stop#获取私有函数 def timelimited(timeout): def decorator(function): def decorator2(*args,**kwargs): class TimeLimited(Thread): def __init__(self,_error= None,): Thread.__init__(self) self._error = _error def run(self): try: self.result = function(*args,**kwargs) except Exception,e: self._error =e def _stop(self): if self.isAlive(): ThreadStop(self) t = TimeLimited() t.start() t.join(timeout) if isinstance(t._error,TimeoutException): t._stop() raise TimeoutException('timeout for %s' % (repr(function))) if t.isAlive(): t._stop() raise TimeoutException('timeout for %s' % (repr(function))) if t._error is None: return t.result return decorator2 return decorator @timelimited(2) def fn_1(secs): time.sleep(secs) return 'Finished' if __name__ == "__main__": print fn_1(4)

 

希望本文所述对大家的Python程序设计有所帮助。

 

大家介绍了关于Python 2.x如何设置命令执行超时时间的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

在Python2.x中的几个用来执行命令行的库或函数在执行命令是均不能设置一个命令执行的超时时间,用来在命令执行时间超时时终端这个命令的执行,这个功能在3.x(?)中解决了,但是在2.x还是只能自己实现。下面话不多说了,来一起看看详细的介绍吧。

下面就简单实现了一个版本:

import subprocess from threading import Timer     def call(args, timeout): p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)   timer = Timer(timeout, lambda process: process.kill(), [p])   try: timer.start() stdout, stderr = p.communicate() return_code = p.returncode return (stdout, stderr, return_code) finally: timer.cancel()

测试

print call(['hostname'], 2) print call(['ping', 'www.baidu.com'], 2)

 

python程序运行超过时长强制退出方式,防止程序卡死;主要两种方式:1、程序内部设置时长,超过退出

import datetime import time import datetime starttime = datetime.datetime.now() #long running endtime = datetime.datetime.now() print (endtime – starttime).seconds 1 2 3 4 5 6 7 8 9 import datetime import time t1 = time.time() t1 = time.localtime(t1).tm_hour print(t1) while 1: if time.localtime(time.time()).tm_hour - t1


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有